import uuid

from django.db import models
from django.contrib.contenttypes.fields import GenericRelation
from ckeditor.fields import RichTextField
from django.db.models import F

from accounts.models import User
from system.models import ImageFile
from utils import constants, common
# Create your models here.




class Classify(common.CommonModel):
    """商品的分类"""
    uid = models.UUIDField('分类ID', default=uuid.uuid4, editable=False)
    # 商品分类存在子类的情况下， 绑定自身
    parent = models.ForeignKey('self', related_name='children', null=True, blank=True)
    img = models.ImageField('分类主图', upload_to='classify')
    code = models.CharField('编码', max_length=32, null=True, blank=True)
    name = models.CharField('名称', max_length=12)
    desc = models.CharField('描述', max_length=64, null=True, blank=True)
    reorder = models.SmallIntegerField('排序', default=0)
    is_valid = models.BooleanField('是否有效', default=True)

    class Meta:
        db_table = 'mall_classify'
        verbose_name = '商品分类'
        verbose_name_plural = '商品分类'
        ordering = ['-reorder']

    def __str__(self):
        return '{}:{}'.format(self.code, self.name)

class Tag(common.CommonModel):
    """商品的标签"""
    uid = models.UUIDField('标签ID', default=uuid.uuid4, editable=False)
    img = models.ImageField('主图', upload_to='tags', null=True, blank=True)
    code = models.CharField('编码', max_length=32, null=True, blank=True)
    name = models.CharField('名称', max_length=12)
    reorder = models.SmallIntegerField('排序', default=0)
    is_valid = models.BooleanField('是否有效', default=True)

    class Meta:
        db_table = 'mall_tag'
        verbose_name = '商品标签'
        verbose_name_plural = '商品标签'
        ordering = ['-reorder']

    def __str__(self):
        return '{}:{}'.format(self.code, self.name)

class Product(common.CommonModel):
    """商品"""
    uid = models.UUIDField('商品ID', default=uuid.uuid4, editable=False)
    name = models.CharField('商品名称', max_length=128)
    desc = models.CharField('简单描述', max_length=256, null=True, blank=True)
    # content = models.TextField('商品描述')

    # 富文本
    content = RichTextField('商品描述')

    types = models.SmallIntegerField('商品类型', default=constants.PRODUCT_TYPE_ACTUAL, choices=constants.PRODUCT_TYPES_CHOICES)
    price = models.IntegerField('兑换价格(积分兑换)')
    origin_price = models.FloatField('原价')
    img = models.ImageField('主图', upload_to='%Y%m/product')
    buy_link = models.CharField('购买链接', max_length=256, null=True, blank=True)
    reorder = models.SmallIntegerField('排序', default=0)
    status = models.SmallIntegerField('商品状态', default=constants.PRODUCT_STATUS_LOST,
                                      choices=constants.PRODUCT_STATUS_CHOICES)
    sku_count = models.IntegerField('库存', default=0)
    remain_count = models.IntegerField('剩余库存', default=0)
    view_count = models.IntegerField('浏览次数', default=0)
    score = models.FloatField('商品的评分', default=10.0)
    is_valid = models.BooleanField('是否有效', default=True)

    tags = models.ManyToManyField(Tag, verbose_name='标签', related_name='tags',
                                  null=True,
                                  blank=True)  # 多对多
    Classes = models.ManyToManyField(Classify, verbose_name='分类', related_name='classes',
                                     null=True,
                                     blank=True)  # 多对多
    # 反向关联
    banners = GenericRelation(ImageFile, verbose_name='banner图', related_query_name='banners', on_delete=models.CASCADE)


    class Meta:
        db_table = 'mall_product'
        verbose_name = '商品信息'
        verbose_name_plural = '商品信息'
        ordering = ['-reorder']

    def update_store_count(self, count):
        """
        更改商品的库存信息
        :param count:
        :return:
        """
        # 减去库存，F()函数从数据库操作层面修改数据，可避免同时操作时竞态条件
        self.remain_count = F('remain_count') - abs(count)
        # 保存数据库
        self.save()
        # 刷新数据库
        self.refresh_from_db()

    def __str__(self):
        return self.name

class Comments(common.CommonModel):
    """商品评价"""
    # 评分的维度
    # 匿名
    # 置顶，排序
    # 关联图片
    product = models.ForeignKey(Product, related_name='comments', verbose_name='商品', on_delete=models.CASCADE),
    user = models.ForeignKey(User, related_name='comments', verbose_name='用户', on_delete=models.CASCADE),
    desc = models.CharField('评价内容', max_length=256),
    reorder = models.SmallIntegerField('排序', default=0),
    is_anonymous = models.BooleanField('是否匿名', default=True),

    score = models.FloatField('商品评分', default=10.0)
    score_deliver = models.FloatField('配送服务分', default=10.0)
    score_package = models.FloatField('快递包装分', default=10.0)
    score_speed = models.FloatField('送货速度分', default=10.0)

    is_valid = models.BooleanField('是否有效', default=True)
    img_list = GenericRelation(ImageFile, verbose_name='评价晒图', related_query_name='img_list', on_delete=models.CASCADE)

    class Meta:
        db_table = 'mall_comments'